import React, { useState } from 'react';
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  StyleSheet,
  Alert,
  Dimensions,
  SafeAreaView
} from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import axios from 'axios';

const screenWidth = Dimensions.get('window').width;

// 添加新的 state
// 添加状态控制
const ResetPassword = ({ navigation }) => {
  const [email, setEmail] = useState('');
  const [verificationCode, setVerificationCode] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState(''); // 新增
  const [countdown, setCountdown] = useState(0);
  const [loading, setLoading] = useState(false);
  const [keyVisible, setKeyVisible] = useState(false);  // 添加密码显示状态
  const [confirmKeyVisible, setConfirmKeyVisible] = useState(false);  // 添加确认密码显示状态

  const sendVerificationCode = async () => {
    if (!email) {
      Alert.alert('提示', '请输入邮箱地址');
      return;
    }

    try {
      setLoading(true);
      const response = await axios.post('http://124.222.104.145:8003/user/send-verification-code/', {
        email,
        action: 'reset_password'
      });

      if (response.data.success) {
        Alert.alert('成功', response.data.message);
        setCountdown(60);
        const timer = setInterval(() => {
          setCountdown((prev) => {
            if (prev <= 1) {
              clearInterval(timer);
              return 0;
            }
            return prev - 1;
          });
        }, 1000);
      }
    } catch (error) {
      Alert.alert('错误', error.response?.data?.message || '发送验证码失败');
    } finally {
      setLoading(false);
    }
  };

  // 修改重置密码处理函数
  const handleResetPassword = async () => {
    if (!email || !verificationCode || !newPassword || !confirmPassword) {
      Alert.alert('提示', '请填写所有必填项');
      return;
    }

    if (newPassword !== confirmPassword) {
      Alert.alert('提示', '两次输入的密码不一致');
      return;
    }

    try {
      setLoading(true);
      const response = await axios.post('http://124.222.104.145:8003/user/reset-password/', {
        email,
        verification_code: verificationCode,
        new_password: newPassword  // 只发送新密码
      });

      if (response.data.success) {
        Alert.alert('成功', '密码重置成功', [
          {
            text: '确定',
            onPress: () => navigation.navigate('LoginPage')
          }
        ]);
      }
    } catch (error) {
      Alert.alert('错误', error.response?.data?.message || '重置密码失败');
    } finally {
      setLoading(false);
    }
  };

  // 修改输入框顺序和添加确认密码输入框
  return (
    <SafeAreaView style={[styles.container, { justifyContent: 'center' }]}>
      <View 
        style={{ 
          paddingBlock: 12, 
          paddingHorizontal: 30, 
          paddingTop: 30,
          paddingRight: 50,
          backgroundColor: "rgb(230, 230, 230)", 
          position: 'absolute',
          top: 0,
          left: 0,
          right: 0,
        }}
      >
        <TouchableOpacity onPress={() => navigation.goBack()}>
          <Icon name="angle-left" size={30} color="#000"/>
        </TouchableOpacity>
      </View>

      <View style={{ alignItems: 'center', marginBottom: 30 }}>
        <Text style={styles.title}>重置密码</Text>
      </View>

      <View style={styles.inputContainer}>
        <View style={styles.inputWrapper}>
          <TextInput
            style={[styles.input, { paddingRight: 60 }]}
            placeholder="请输入邮箱"
            value={email}
            onChangeText={setEmail}
            keyboardType="email-address"
          />
          <Text style={styles.separator}>|</Text>
          <Icon name="envelope" size={20} style={styles.icon} />
        </View>

        <View style={styles.inputWrapper}>
          <TextInput
            style={[styles.input, { paddingRight: 60 }]}
            placeholder="请输入新密码"
            value={newPassword}
            onChangeText={setNewPassword}
            secureTextEntry={!keyVisible}
          />
          <Text style={styles.separator}>|</Text>
          <TouchableOpacity 
            onPress={() => setKeyVisible(!keyVisible)}
            style={{
              position: 'absolute',
              right: 0,
              top: 0,
              width: 50,
              height: '100%',
              justifyContent: 'center',
              alignItems: 'flex-end',
              paddingRight: 15,
            }}
          >
            <Icon 
              name={!keyVisible ? "lock" : "unlock"} 
              size={20} 
              color="rgba(100, 100, 100, 0.8)"
            />
          </TouchableOpacity>
        </View>

        <View style={styles.inputWrapper}>
          <TextInput
            style={[styles.input, { paddingRight: 60 }]}
            placeholder="请确认新密码"
            value={confirmPassword}
            onChangeText={setConfirmPassword}
            secureTextEntry={!confirmKeyVisible}
          />
          <Text style={styles.separator}>|</Text>
          <TouchableOpacity 
            onPress={() => setConfirmKeyVisible(!confirmKeyVisible)}
            style={{
              position: 'absolute',
              right: 0,
              top: 0,
              width: 50,
              height: '100%',
              justifyContent: 'center',
              alignItems: 'flex-end',
              paddingRight: 15,
            }}
          >
            <Icon 
              name={!confirmKeyVisible ? "lock" : "unlock"} 
              size={20} 
              color="rgba(100, 100, 100, 0.8)"
            />
          </TouchableOpacity>
        </View>

        <View style={styles.inputWrapper}>
          <TextInput
            style={[styles.input, { paddingRight: 100 }]}
            placeholder="请输入验证码"
            value={verificationCode}
            onChangeText={setVerificationCode}
            keyboardType="number-pad"
            maxLength={6}
          />
          <Text style={[styles.separator, { right: 80 }]}>|</Text>
          <TouchableOpacity 
            style={[styles.codeButton, countdown > 0 && styles.disabledButton]}
            onPress={sendVerificationCode}
            disabled={countdown > 0 || loading}
          >
            <Text style={styles.codeButtonText}>
              {countdown > 0 ? `${countdown}s` : '获取验证码'}
            </Text>
          </TouchableOpacity>
        </View>

        <TouchableOpacity 
          style={[styles.submitButton, loading && styles.disabledButton]}
          onPress={handleResetPassword}
          disabled={loading}
        >
          <Text style={styles.submitButtonText}>
            {loading ? '提交中...' : '重置密码'}
          </Text>
        </TouchableOpacity>
      </View>
    </SafeAreaView>
  );
};

// 添加分隔符样式
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  title: {
    fontSize: 30,
    fontWeight: "bold",
  },
  inputContainer: {
    width: '100%',
    alignItems: 'center',
  },
  inputWrapper: {
    width: screenWidth * 0.7,
    marginBottom: 20,
    position: 'relative',
  },
  input: {
    backgroundColor: 'rgba(173, 173, 173, 0.42)',
    borderRadius: 8,
    paddingHorizontal: 20,
    height: 36,
    width: screenWidth * 0.7,
    fontSize: 15,
    fontWeight: 'normal',
    textAlignVertical: 'center',
    paddingTop: 8,  // 添加这一行
    paddingBottom: 8,  // 添加这一行
  },
  icon: {
    position: 'absolute',
    right: 15,
    top: 8,
    color: 'rgba(100, 100, 100, 0.8)',
  },
  separator: {
    fontSize: 30, 
    fontWeight: 'light', 
    position: 'absolute', 
    right: 40, 
    bottom: 0, 
    color: 'rgba(122, 122, 122, 0.5)'
  },
  codeButton: {
    position: 'absolute',
    right: 0,
    top: 0,
    backgroundColor: 'rgb(107, 142, 195)',
    height: '100%',
    paddingHorizontal: 15,
    borderRadius: 8,
    justifyContent: 'center',
    alignItems: 'center',
  },
  disabledButton: {
    backgroundColor: 'rgba(107, 142, 195, 0.5)',
  },
  codeButtonText: {
    color: '#fff',
    fontSize: 14,
    fontWeight: 'bold',
  },
  submitButton: {
    backgroundColor: 'rgb(107, 142, 195)',
    width: screenWidth * 0.7,
    height: 37,
    borderRadius: 8,
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 20,
  },
  submitButtonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: 'bold',
  },
});

export default ResetPassword;